const Router = require('koa-router')
const passport = require('koa-passport')
const router = new Router()
const mongoose = require('mongoose')

const Blood = require('../../models/Blood')
const Volunteer = require('../../models/Volunteer')
const dateOperate = require('../../utils/dateFormat').dateOperate
const formatDate = require('../../utils/dateFormat').formatDate

// 引入校验规则
const validateBloodInput = require('../../validation/blood')
// const { findById } = require('../../models/Blood')

// passport 验证, 放在路由参数内
// passport.authenticate('jwt', { session: false }), 

/**
 * @route GET /api/blood/test
 * @desc 测试接口地址
 * @access public
 */
router.get('/report', async ctx => {
  let findResult = await Blood.aggregate([
    { $group: { "_id": "$bloodType", count: { $sum: 1 } } }
  ])
  const keyMap = {
    '_id': 'name',
    'count': 'value'
  }
  for (let i in findResult) {
    const obj = findResult[i]
    for (let key in obj) {
      let newKey = keyMap[key]
      if (newKey) {
        obj[newKey] = obj[key]
        delete obj[key]
      }
    }
  }
  for (let i in findResult) {
    if (!findResult[i].name) {
      findResult.splice(i, 1)
    }
  }
  ctx.status = 200
  ctx.body = findResult
})
/**
 * @description 血量报表
 */
router.get('/vreport', async ctx => {
  let findResult = await Blood.aggregate([
    { $group: { "_id": "$bloodVolume", count: { $sum: 1 } } }
  ])
  const keyMap = {
    '_id': 'name',
    'count': 'value'
  }
  for (let i in findResult) {
    const obj = findResult[i]
    for (let key in obj) {
      let newKey = keyMap[key]
      if (newKey) {
        obj[newKey] = obj[key]
        delete obj[key]
      }
    }
  }
  for (let i in findResult) {
    findResult[i].name = findResult[i].name + 'mm'
    if (!findResult[i].name) {
      findResult.splice(i, 1)
    }
  }
  ctx.status = 200
  ctx.body = findResult
})
/**
 * @route POST /api/blood/add
 * @description 添加一个血袋
 * @access public
 */
router.post('/add', async ctx => {
  const { errors, isValid } = validateBloodInput(ctx.request.body)
  const { volunteerId, bloodVolume, drawDate, drawer, shelfLife, isQualified, remark } = ctx.request.body
  // console.log('ctx.request.body', ctx.request.body)
  if (!isValid) {
    ctx.status = 400
    ctx.body = errors
    return
  }
  // console.log(body.userId)
  // 先通过志愿者id找到志愿者 然后再把志愿者id存到血袋内实现关联
  if (!volunteerId) {
    ctx.status = 400
    ctx.body = {
      msg: '该志愿者不存在, 请添加志愿者'
    }
    return
  }
  const volunteer = await Volunteer.findById(volunteerId)
  // 如何判断血袋重复性?
  const newBlood = new Blood({
    bloodVolume,
    // 日期默认当天
    drawDate,
    drawer,
    shelfLife,
    isQualified,
    remark,
    volunteerId,
    expireDate: formatDate(dateOperate(drawDate, shelfLife, true), true),
    bloodType: volunteer.bloodType
  })
  await newBlood
    .save()
    .then(blood => {
      ctx.body = blood
    })
    .catch(err => {
      console.log(err)
    })
  // console.log(volunteer)
})
/**
 * @description 
 * @route /api/blood/page
 * @access private
 */
router.get('/page', async ctx => {
  const query = ctx.request.query
  let page = Number(query.page) ? Number(query.page) : 1
  let size = Number(query.per_page) ? Number(query.per_page) : 9999
  //  
  let bloodType = query.bloodType ? new RegExp(query.bloodType) : /[\s\S]*/
  let skip = (page - 1) * size
  let findResult = await Blood.aggregate([
    {
      $lookup: {
        from: 'volunteers',
        localField: 'volunteerId',
        foreignField: '_id',
        as: 'volunteer'
      }
    },
    {
      $match: { bloodType, isDeleted: 0 }
    },
  ]).skip(skip).limit(size).collation({ locale: 'en_US' }).sort({ drawDate: -1 })
  let total = findResult.length
  // console.log(findResult)
  let length = findResult.length
  for (let i = 0; i < length; i++) {
    findResult[i].volunteerName = findResult[i].volunteer[0].name
    findResult[i].volunteerId = findResult[i].volunteer[0]._id
    findResult[i].bloodType = findResult[i].volunteer[0].bloodType
    delete findResult[i].volunteer
  }
  ctx.status = 200
  ctx.body = {
    current_page: page,
    per_page: size,
    total,
    data: findResult
  }
})
/**
 * @desc 获取过期血液 分页
 */
router.get('/outdated', async ctx => {
  const query = ctx.request.query
  let page = Number(query.page) ? Number(query.page) : 1
  let size = Number(query.per_page) ? Number(query.per_page) : 9999
  let skip = (page - 1) * size
  let findResult = await Blood.aggregate([
    {
      $lookup: {
        from: 'volunteers',
        localField: 'volunteerId',
        foreignField: '_id',
        as: 'volunteer'
      }
    },
    {
      $match: {
        // reposId: '6098d880b0d88c4004ac6251',
        isOutdated: 1,
        isDeleted: 0
      }
    }
  ]).skip(skip).limit(size).collation({ locale: 'en_US' }).sort({ drawDate: -1 })
  let length = findResult.length
  for (let i = 0; i < length; i++) {
    findResult[i].volunteerName = findResult[i].volunteer[0].name
    findResult[i].volunteerId = findResult[i].volunteer[0]._id
    findResult[i].bloodType = findResult[i].volunteer[0].bloodType
    delete findResult[i].volunteer
  }
  let totalElement = await Blood.countDocuments({ isOutdated: 1 })
  ctx.status = 200
  ctx.body = {
    current_page: page,
    per_page: size,
    total: totalElement,
    data: findResult
  }
})
/**
 * @description 删除一个血袋
 */
router.post('/delete', async ctx => {
  const id = ctx.request.body.id
  try {
    const updateResult = await Blood.findByIdAndUpdate(id, { isDeleted: 1 })
    if (updateResult) {
      ctx.status = 200
      ctx.body = updateResult
    } else {
      ctx.status = 400
      ctx.response.status = 400
      ctx.response.message = '数据库中无该条数据'
      ctx.body = {
        msg: '删除失败'
      }
    }
  } catch { }
})
/**
 * @description 修改一个血袋的信息
 */
router.post('/edit', async ctx => {
  const body = ctx.request.body,
    id = ctx.request.body._id

  try {
    const updateResult = await Blood.findByIdAndUpdate(id, body)
    if (updateResult) {
      ctx.status = 200
      ctx.body = updateResult
    } else {
      ctx.status = 400
      ctx.response.status = 400
      ctx.response.message = '数据库中无该条数据'
      ctx.body = {
        msg: '修改失败'
      }
    }
  } catch { }
})

/**
 * @route api/blood/get
 * @access private
 * @description 查看志愿者献血记录(血袋)
 */
router.get('/get', async ctx => {
  // const body = ctx.request.body
  const query = ctx.request.query
  try {
    const findResult = await Blood.find({ volunteerId: mongoose.Types.ObjectId(query.volunteerId) })
    ctx.status = 200
    ctx.body = findResult
  } catch (err) {
    ctx.status = 400
    ctx.body = {
      msg: ''
    }
  }
})

module.exports = router.routes()